#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

void mysys(char *command)
{
    char* argv[16];
    int j, last_i;
    j = last_i = 0;
    for (int i = 0; 1; i++)
    {
        if (command[i] == ' ')
        {
            command[i] = 0;
            // printf("here1 %d\n", i);
            argv[j] = (char *)malloc(sizeof(char)*128);
            strcpy(argv[j++], command+last_i);
            last_i = i+1;
        }
        else if (command[i] == 0)
        {
            // printf("here2\n");
            argv[j] = (char *)malloc(sizeof(char)*128);
            strcpy(argv[j++], command+last_i);
            break;
        }
    }

    if (strcmp(argv[0], "exit") == 0)
    {
        exit(0);
    }
    else if (strcmp(argv[0], "cd") == 0)
    {
        chdir(argv[1]);
    }
    else if (strcmp(argv[0], "pwd") == 0)
    {
        char path[512];
        getcwd(path, sizeof(path));
        printf("%s\n", path);
    }
    else
    {
        pid_t pid = fork();

        if (pid == 0)
        {
            argv[j] = (char *)malloc(sizeof(char)*128);
            argv[j] = NULL;
            // printf("%d\n", j);
            execvp(argv[0], argv);
            // exit(1);
        }
        else
        {
            wait(NULL);
        }
    }
}

int main()
{
    char buf[512];
    while (1)
    {
        write(1, ">", 2);
        memset(buf, 0, sizeof(buf));
        int cnt = read(0, buf, sizeof(buf));
        buf[cnt-1] = 0;

        mysys(buf);
    }
}